//
//  SFStatusListViewModel.swift
//  SFWeiboPro
//
//  Created by happy on 2017/9/12.
//  Copyright © 2017年 happy. All rights reserved.
//

import Foundation

//上拉刷新最大的尝试次数
private let maxPullupTryTimes = 1
///微博数据的加载
class SFStatusListViewModel {
    
    //微博模型数组懒加载
    lazy var statusArray = [SFStatusViewModel]()
    //上拉刷新错误次数
    private var pullupErrorTimes = 0
    
    //加载微博数据模型
    func loadStatus(pullUp: Bool, completion: @escaping (_ isSuccess: Bool, _ shouldRefresh: Bool)->()) {
        
        if pullUp && pullupErrorTimes > maxPullupTryTimes {
            
            completion(false, false)
            
            return
        }
        
        let since_id = pullUp ? 0 : statusArray.first?.status.id ?? 0
        
        let max_id = !pullUp ? 0 : statusArray.last?.status.id ?? 0
        
        print("\(since_id)----\(max_id)")
        
        SFNetworkManager.shareManager.statusList(since_id: since_id, max_id: max_id) { (list, isSuccess) in
            
            
            if !isSuccess {
                
                completion(false, false)
                
                return
            }
            
            var array = [SFStatusViewModel]()
            
            for dict in list ?? [] {
                
//                print(dict["pic_urls"])
                
                guard let status =  SFStatus.yy_model(with: dict) else {
                    continue
                }
                
                array.append(SFStatusViewModel(model: status))
                
            }
            
            //guard守护
//            guard let array = NSArray.yy_modelArray(with: SFStatus.self, json: list ?? []) as? [SFStatus] else{
//                
//                completion(isSuccess, false)
//                return
//            }
            
            print("刷新\(array.count)条数据")
            
            if pullUp {
                self.statusArray += array
            }
            else {
                self.statusArray = array + self.statusArray
            }
            
            if pullUp && array.count == 0 {
                
                self.pullupErrorTimes += 1
                
                completion(isSuccess, false)
            }
            else {
                completion(isSuccess, true)
            }
            
            
        }
        
    }
}
